package com.zx.deploy.common.utils;


import org.apache.commons.io.FilenameUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by IBM on 2018/4/4.
 */
public class FileUtil {
    public static List<String> listFiles(String path,String ext){
        File dir = new File(path);
        File[] files = dir.listFiles((dir1, name) -> {
           if(StringUtils.isEmpty(ext)) {
               return true;
           }
           if(FilenameUtils.getExtension(name).equals(ext)){
               return true;
           }
           return false;
       });
        Map<Long,String> filenamesMap = new TreeMap<>((o1, o2) -> (int)(o2-o1));
        if(files == null){
            return new ArrayList<>();
        }
        for(File file:files){
            filenamesMap.put(file.lastModified(),file.getName());
        }
        List<String> filenames = new ArrayList<>(filenamesMap.values());
        int length = filenames.size()>=20?20:filenames.size();
        return filenames.subList(0,length);
    }

    public static File getFile(String path){
        File file = new File(path);
        if(!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;

    }
}
